package fi.hell.lunchit

import fi.hell.enums.RestaurantSort

class RestaurantTagLib {

    def orderedRestaurantList = { attrs ->

        String order = (attrs.order == "desc" || attrs.order == "asc") ? attrs.order : "desc"
        RestaurantSort sort

        if (attrs.sort) {
            try {
                sort = Enum.valueOf(RestaurantSort.class, attrs.sort?.toUpperCase())
            } catch (Exception e) {
                flash.unsupportedSorting = g.message(code:"sortingParameterNotAvailable", default:"Sorting with given value ({0}) is not supported", args:[params.sort])
                log.error e.getMessage()
                sort = grailsApplication.config.restaurant.defaultSorting
            }
        } else {
            sort = grailsApplication.config.restaurant.defaultSorting
        }

        List<Restaurant> restaurants = Restaurant.orderedList(sort, order)

        out << g.render(template:"restaurants", model:['sort':sort, 'order':order, 'currentVote':attrs.currentVote, 'currentRound':attrs.currentRound, 'restaurants':restaurants])
    }
}
